<?php

/*
  Contiene la classe che gestisce i template del sito
 */
require_once "include/template2.inc.php";
require_once "include/db_manager.inc.php";

Class RSS_Manager {

    private $template;

    /**
     * 
     * @param type $name Description meta Definisce i metavalori per RSS file 
     */
    public function __construct($schema, $meta = null) {

        $this->setMeta($schema, $meta);
    }

    public function __destruct() {
        //$this->template->close();
    }

    public function save($dir) {
        $myfile = fopen($dir . '/rss.xml', "w") or die("Unable to open file!");
        fwrite($myfile, $this->getRssContent());
        fclose($myfile);
    }
    public function saveType($dir,$type) {
        $myfile = fopen($dir . '/rss_'.$type.'.xml', "w") or die("Unable to open file!");
        fwrite($myfile, $this->getRssContent());
        fclose($myfile);
    }
    
    public function getTemplate() {
        return $this->template;
    }

    public function setMeta($schema, $meta) {
        $this->template = new Template(Config::$site_skin . $schema);
        foreach ($meta as $key => $value) {
            $this->setContentString($key, $value);
        }
    }

    public function setFeeds($data) {
        while ($row = $data->fetch_array(MYSQLI_ASSOC)) {
            foreach ($row as $key => $value) {
                if (!strcmp($key, "uri")) {
                    $file=  getcwd().'/' . Config::$site_upload .$value;
                    $type=getimagesize($file);
                    $this->setContentString("item_enclosure", Config::$site_name . '/' . Config::$site_upload .$value);
                    $this->setContentString("item_type", $type['mime']);
                    $this->setContentString("item_length", filesize($file));
                } else if (!strcmp($key, "description")) {
                    $introlen = 137;
                    $descrizione = strip_tags($row['description']);
                    $descr = (strlen($descrizione) > $introlen) ? substr($descrizione, 0, strpos($descrizione, ' ', $introlen)) . "..." : $descrizione;
                    $this->setContentString("item_description", $descr);
                } else {
                    $this->setContentString("item_" . $key, $value);
                }
            }
        }
    }

    /**
     * Trova l'etichetta $content e la rimpiazza col
     * url di un immagine
     * @param type $content placeholder da riempire
     *
     */
    public function setContent($content) {
        $this->template->setContent($content);
    }

    /**
     * trova l'etichetta $content nel $body e la rimpiazza col
     * contenuto $string
     * @param type $content placeholder da riempire
     * @param type $string contenuto utilizzato per riempire
     */
    public function setContentString($content, $string) {
        $this->template->setContent($content, $string);
    }
    public function getRssContent() {
        return $this->template->get();
    }

}

?>